/*
 * Created on 10/10/2011 - 16:01 AM
 */
package sembr.vtk.reader;

import vtk.*;

/**
 *
 * @author Adriano
 */
public class JpgReader extends ReaderBase
{
    private vtkJPEGReader reader;
    private vtkPolyData polyData;
    private vtkActor sourceActor;
    private vtkPanel panel;

    public JpgReader(String path) 
    {
        reader = new vtkJPEGReader();
        sourceActor = new vtkActor();
        panel = new vtkPanel();
        // set reader
        setReader(path);
        setPolyData();
        createScene();
    }
    
    private void setReader(String path)
    {
        reader.SetFilePrefix(path + "sembr.dxf.presentation/icons/fields/fonte"); 
        reader.SetDataByteOrderToBigEndian();
        reader.SetDataExtent(0, 255, 0, 238, 1, 20); 
        reader.SetFilePattern("%s.%02d.jpg"); 
        reader.Update();   
    }
    
    private void createScene()
    {                      
        vtkDataSetMapper mapper2 = new vtkDataSetMapper();
        mapper2.SetInput(getPolyData());
        mapper2.SetColorModeToMapScalars();
       
        sourceActor.SetMapper(mapper2);
        sourceActor.SetOrientation(-19., 50., 20.);
        //sourceActor.SetScale(0.1);
                
        vtkCamera camera1 = new vtkCamera();
        camera1.SetViewUp(0.00, 1.00, 0.00);
        camera1.SetPosition(2, 2, 2);
        camera1.SetFocalPoint(0, 0, 0); 
        
        panel = new vtkPanel();
        panel.GetRenderer().AddActor(sourceActor);
        panel.GetRenderer().SetActiveCamera(camera1);    
        panel.GetRenderer().SetBackground(255., 255., 255.);
        //panel.GetRenderer().ResetCamera();
    }
    
     /**
     * @return the sourceActor
     */
    public vtkActor getSourceActor() 
    {
        return sourceActor;
    }
    
    /**
     * @return the panel
     */
    public vtkPanel getPanel() 
    {
        return panel;
    }

    @Override
    public vtkPolyData getPolyData() 
    {
        polyData = contourImageData(reader.GetOutput());
        return polyData;
    }
    
    private void setPolyData()
    {
        polyData = scaleSource(contourImageData(reader.GetOutput()));
    }
    
    private vtkPolyData contourImageData(vtkImageData imageData)
    {
        vtkContourFilter contourImage = new vtkContourFilter();
        contourImage.SetInput(imageData);
        contourImage.GenerateValues(1, 5, 6);
        contourImage.Update();
        
        return contourImage.GetOutput();
    }
    
    private vtkPolyData scaleSource(vtkPolyData pd)
    {
        vtkTransform transformer = new vtkTransform();
        transformer.PostMultiply();
        transformer.Scale(0.00001, 0.00001, 0.00001);
        transformer.Update();
        
        vtkTransformPolyDataFilter transformerFilter = new vtkTransformPolyDataFilter();
        transformerFilter.SetTransform(transformer);
        transformerFilter.SetInput(pd);
        transformerFilter.Update();  
        
        return transformerFilter.GetOutput();
    }
}
